﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
    public abstract class SQLHelper
    {
        /// <summary>
        /// 连接字符串。读取webconfig文件
        /// </summary>
        public static readonly string sqlConnectionString = ConfigurationManager.ConnectionStrings["CONNSTR"].ConnectionString;
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
        /// <summary>
        /// 准备命令执行
        /// </summary>
        /// <param name="cmd">SqlCommand命令</param>
        /// <param name="conn">SqlConnection连接</param>
        /// <param name="trans">SqlTransaction事务</param>
        /// <param name="cmdType">Cmd type是SQL语句还是存储过程</param>
        /// <param name="cmdText">Command text存储过程名或SQL语句</param>
        /// <param name="cmdParms">SqlParameters参数</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {
            //将一些参数，集中初始化到命令对象上面。
            //如果连接未打开
            if (conn.State != ConnectionState.Open)
                conn.Open();//打开

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)//如果有事务
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;//命令类型

            if (cmdParms != null)//如果有参数
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);//添加到参数列表
            }


        }


        /// <summary>
        /// 执行查询命令或存储过程。返回一个受影响的行数
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="commandType">命令类型</param>
        /// <param name="commandText">存储过程名或SQL语句</param>
        /// <param name="commandParameters">一组参数</param>
        /// <returns>返回受影响的行数</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();//CMD初始化完成。开始执行命令
                cmd.Parameters.Clear();
                return val;
            }
        }
        /// <summary>
        /// 执行查询命令或存储过程。返回一个受影响的行数
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">连接对象</param>
        /// <param name="commandType">命令类型</param>
        /// <param name="commandText">存储过程名或SQL语句</param>
        /// <param name="commandParameters">一组参数</param>
        /// <returns>返回受影响的行数</returns>
        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }
        /// <summary>
        /// 执行查询命令或存储过程,带事务。返回一个受影响的行数
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">连接对象</param>

        /// <param name="trans">事务对象</param>
        /// <param name="commandType">命令类型</param>
        /// <param name="commandText">存储过程名或SQL语句</param>
        /// <param name="commandParameters">一组参数</param>
        /// <returns>返回受影响的行数</returns>
        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }



        /// <summary>
        /// 返回一个数据阅读器对象
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="commandType">命令类型</param>
        /// <param name="commandText">存储过程名或SQL语句</param>
        /// <param name="commandParameters">一组参数</param>
        /// <returns>SqlDataReader对象</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        /// <summary>
        /// 执行查询，并返回第一行第一列
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="commandType">命令类型</param>
        /// <param name="commandText">存储过程名或SQL语句</param>
        /// <param name="commandParameters">一组参数</param>
        /// <returns>object对象</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }


        /// <summary>
        /// 执行查询，并返回第一行第一列
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">连接对象</param>
        /// <param name="commandType">命令类型</param>
        /// <param name="commandText">存储过程名或SQL语句</param>
        /// <param name="commandParameters">一组参数</param>
        /// <returns>object对象</returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 在缓存中添加一组参数
        /// </summary>
        /// <param name="cacheKey">缓存集合中的键</param>
        /// <param name="cmdParms">一组参数</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// 找到缓存中的一组参数
        /// </summary>
        /// <param name="cacheKey">要查找的缓存中的键</param>
        /// <returns>缓存中的参数数组</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }


    }
}
